package com.dcy.gateway.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：dcy
 * @Description: 网关统一错误拦截
 * @Date: 2021/5/19 8:52
 */
@Slf4j
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {

    private static final String CODE = "code";
    private static final String MSG = "msg";

    public JsonExceptionHandler(ErrorAttributes errorAttributes, WebProperties.Resources resourceProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        int code = 500;
        final Throwable error = super.getError(request);
        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = 404;
        } else if (error instanceof SaTokenException) {
            code = 200;
        }
        log.error("JsonExceptionHandler {}", error.toString());
        error.printStackTrace();
        return response(code, this.buildMessage(request, error));
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return (int) errorAttributes.get(CODE);
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        String message = "";
        if (ex instanceof NotLoginException) {
            // 判断场景值，定制化异常信息
            NotLoginException notLoginException = (NotLoginException) ex;
            switch (notLoginException.getType()) {
                case NotLoginException.NOT_TOKEN:
                    message = NotLoginException.NOT_TOKEN_MESSAGE;
                    break;
                case NotLoginException.INVALID_TOKEN:
                    message = NotLoginException.INVALID_TOKEN_MESSAGE;
                    break;
                case NotLoginException.TOKEN_TIMEOUT:
                    message = NotLoginException.TOKEN_TIMEOUT_MESSAGE;
                    break;
                case NotLoginException.BE_REPLACED:
                    message = NotLoginException.BE_REPLACED_MESSAGE;
                    break;
                case NotLoginException.KICK_OUT:
                    message = NotLoginException.KICK_OUT_MESSAGE;
                    break;
                default:
                    message = NotLoginException.DEFAULT_MESSAGE;
                    break;
            }
        } else if (ex instanceof NotRoleException) {
            NotRoleException notRoleException = (NotRoleException) ex;
            message = notRoleException.getMessage();
        } else if (ex instanceof NotPermissionException) {
            NotPermissionException notPermissionException = (NotPermissionException) ex;
            message = notPermissionException.getMessage();
        } else {
            message = ex.getMessage();
        }
        return message;
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status       状态码
     * @param errorMessage 异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put(CODE, status);
        map.put(MSG, errorMessage);
        return map;
    }

}
